<template>
  <div>

    <qu-item-save ref="mainForm" v-model="postForm" :update="!!postForm.id" />

    <div v-if="postForm.quType === '99'">

      <h3>小题列表</h3>

      <div v-if="postForm.subList.length > 0" style="display: flex">
        <div class="sub-qu">
          <div v-for="(child,index) in postForm.subList" :id="index" :key="index" style="margin-bottom: 30px; padding-right: 20px">
            <qu-item-save :value="child" :child="true" :update="!!child.id" :exclude-types="['99']" @change="childChange(index, $event)" />
          </div>
        </div>
        <div class="sub-right">
          <el-card :class="{'sub-nav':true, 'sub-nav-scrolled': scrolled}">

            <div style="padding-bottom: 20px">
              <el-button type="primary" style="width: 100%" @click="addChild">添加子题目</el-button>
            </div>

            <div id="subDiv">

              <el-table
                id="subTable"
                :data="postForm.subList"
                style="width: 100%"
                row-key="id"
              >

                <el-table-column
                  prop="title"
                  label="操作区"
                >
                  <template v-slot="scope">

                    <div class="sub-box" @click="goAnchor(scope.$index)">

                      <div class="sub-bar">
                        <div class="sub-type">{{ scope.$index +1 }}  - {{ !scope.row.quType?'请完善':'' }}{{ scope.row.quType | quTypeFilter }}</div>
                        <div class="sub-btn">
                          <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="removeChild(scope.$index)" />
                          <el-button size="mini" icon="el-icon-rank" circle />
                        </div>
                      </div>
                      <div class="sub-content" v-html="$options.filters.clearHtml(scope.row.content)" />

                    </div>

                  </template>

                </el-table-column>

              </el-table>

            </div>
          </el-card>
        </div>
      </div>

      <div v-else style="padding-bottom: 20px">
        <el-card>
          <div style="line-height: 50px; text-align: center; color: #666">点击以下按钮添加一道小题！</div>
          <el-button type="primary" style="width: 100%" @click="addChild">添加子题目</el-button>
        </el-card>

      </div>

    </div>

    <div style="margin-top: 20px">
      <el-button type="primary" @click="submitForm">保存</el-button>
      <el-button type="info" @click="onCancel">返回</el-button>
    </div>

  </div>
</template>

<script>
import Sortable from 'sortablejs'
import { fetchDetail, saveData } from '@/api/qu/qu'
import QuItemSave from './components/QuItemSave'
import { scrollTo } from '@/utils/scroll-to'

export default {
  components: { QuItemSave },
  data() {
    return {
      scrolled: false,
      anchor: -1,
      quId: '',
      postForm: {
        quType: '',
        repoId: '',
        answerList: [],
        subList: []
      }
    }
  },
  watch: {
    'postForm.subList': {
      handler(val) {
        // 初始化小题排序拖动
        if (this.postForm.quType === '99' && val && val.length > 0) {
          setTimeout(() => {
            this.initSortable()
          }, 2000)
        }
      }
    }
  },

  mounted() {
    // 滑动效果
    this.initScroll()
  },
  created() {
    const id = this.$route.params.id
    if (id) {
      this.quId = id
      this.quTypeDisabled = true
      this.fetchData(id)
    } else {
      const repoId = this.$route.query.repoId
      if (repoId != null && repoId !== '') {
        this.postForm.repoId = repoId
      }
    }
  },

  methods: {

    // 查找试题信息
    fetchData(id) {
      fetchDetail(id).then(response => {
        this.postForm = response.data
      })
    },

    // 初始化排序
    initSortable() {
      const that = this
      const table = document.getElementById('subTable').querySelector('.el-table__body-wrapper tbody')
      Sortable.create(table, {
        onEnd({ newIndex, oldIndex }) {
          // 进行排序
          const targetRow = that.postForm.subList.splice(oldIndex, 1)[0]
          that.postForm.subList.splice(newIndex, 0, targetRow)

          // 深拷贝重新赋值
          const sortArray = that.postForm.subList.slice(0)

          // 清空重新赋值
          that.postForm.subList = []
          that.$nextTick(function() {
            that.postForm.subList = sortArray
          })
        }
      })
    },

    // 滑动监听
    initScroll() {
      // 监听滚动条
      window.addEventListener('scroll', () => {
        let scrollTop = 0
        if (document.documentElement && document.documentElement.scrollTop) {
          scrollTop = document.documentElement.scrollTop
        } else if (document.body) {
          scrollTop = document.body.scrollTop
        }

        if (scrollTop > 726) {
          this.scrolled = true
        } else {
          this.scrolled = false
        }
      })
    },

    // 添加子题目
    addChild() {
      if (!this.postForm.subList) {
        this.$set(this.postForm, 'subList', [])
      }

      // 增加一项
      this.postForm.subList.push({ content: '', answerList: [] })
    },

    // 移除子题目
    removeChild(index) {
      // 删除
      this.$confirm(`确实要移除第${index + 1}小题吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.postForm.subList.splice(index, 1)
      })
    },

    // 子题目编辑回调
    childChange(index, val) {
      this.postForm.subList[index] = val
    },

    // 到指定位置
    goAnchor(selector) {
      const anchor = document.getElementById(selector)
      const to = anchor.offsetTop + 80
      scrollTo(to, 620, function() {
        console.log('滑动到指定位置！')
      })

      this.anchor = selector
    },

    submitForm() {
      let rightCount = 0
      this.postForm.answerList.forEach(function(item) {
        if (item.isRight) {
          rightCount += 1
        }
      })

      if (this.postForm.quType === '1') {
        if (rightCount !== 1) {
          this.$message({
            message: '单选题答案只能有一个',
            type: 'warning'
          })

          return
        }
      }

      if (this.postForm.quType === '2') {
        if (rightCount < 2) {
          this.$message({
            message: '多选题至少要有两个正确答案！',
            type: 'warning'
          })

          return
        }
      }

      if (this.postForm.quType === '3') {
        if (rightCount !== 1) {
          this.$message({
            message: '判断题只能有一个正确项！',
            type: 'warning'
          })

          return
        }
      }

      const that = this

      this.$refs.mainForm.validate().then(res => {
        console.log('+++++validate', res)

        if (!res) {
          return
        }

        saveData(this.postForm).then(() => {
          if (!this.postForm.id) {
            this.$confirm('试题添加成功，接下来您要？', '提示', {
              confirmButtonText: '继续添加下一题',
              cancelButtonText: '返回列表',
              type: 'warning'
            }).then(() => {
              // 刷新页面
              this.clearForm()
            }).catch(() => {
              that.$router.push({ name: 'ListQuByRepo', params: { repoId: this.postForm.repoId }})
            })
          } else {
            that.$router.push({ name: 'ListQuByRepo', params: { repoId: this.postForm.repoId }})
          }
        })
      })
    },
    onCancel() {
      this.$router.push({ name: 'ListQuByRepo', params: { repoId: this.postForm.repoId }})
    },
    clearForm() {
      // 清理数据
      this.$refs.mainForm.clear()

      // 移除编辑缓存
      localStorage.removeItem(this.cacheKey)
    }

  }
}
</script>

<style scoped>

.sub-qu{
  flex-grow: 1;
  width: calc(100% - 370px)
}

.sub-right{
  width: 350px;
}

.sub-nav{
  padding: 0px;
  line-height: 40px;
  width: 350px;
}

.sub-nav-scrolled{
  top: 20px;
  z-index: 999;
  right: 20px;
  width: 350px;
  position: fixed;
  overflow-y: auto;
  max-height: calc(100vh - 40px);
}

/deep/
.sub-box{
  cursor: pointer;
  margin: 0px;
}

.sub-box .sub-bar{
  display: flex;
  align-content: center;
  font-weight: 700;
}

.sub-box .sub-type{
  flex-grow: 1;
  display: flex;
  align-items: center
}

.sub-box .sub-btn{
  display: flex;
  align-items: center;
}

.sub-box .sub-content{
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  word-break: break-all;
  color: #888;
  font-size: 12px;
  padding-top: 5px;
}

</style>

